
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Xml;

using Swaf.Gui;

namespace Syrinx.Gui.AspNet.Ajax
{
	public class ActionButton : Swaf.Gui.AspNet2.ActionButton, IAjaxClientControl
	{
		protected static string s_setupScript = @"
var c = new ClientControl(document.getElementById('{1}'), setActionButtonState, getActionButtonState);
c.id = '{1}';
{2}
{0}BizProc.addClientControl(c);
";
		protected static string s_globalScript = @"
function setActionButtonState(stateEl)
{
	try
	{
	this.dhtmlObj.disabled = stateEl.getAttribute('enabled').toLowerCase() == 'true'?false:true;
	this.dhtmlObj.style.display = stateEl.getAttribute('visible').toLowerCase() == 'true'?'inline':'none';
	var label = stateEl.getAttributeNode('label');
	if(label != null)
		this.dhtmlObj.innerHTML = label.text;
	}catch(e){}
}
function getActionButtonState(stateEl)
{
	try{stateEl.setAttribute('action', this.dhtmlObj.name);}catch(e){}
}
";

		public ActionButton()
			:base()
		{
		}

		public ActionButton(ActiveWidget widget)
			:base(widget)
		{
		}

		protected override void OnPreRender(EventArgs e)
		{
			bool setupScript = false;
			List<IAction> actions = null;
			if (!base.m_canceledTrigger)
			{
				actions = BPC.getBizProcActions(Actions);
				if (actions.Count > 0 && (Page is INitobiPage || (Page is NitobiBasePage && ((NitobiBasePage)Page).UsingAjax)))
				{
					setupScript = true;
					UseSubmitBehavior = false;
					string after = "return false;";
					if (AfterClientClick != null)
						after = AfterClientClick;
                    string tpam = TriggerParam==null?"":TriggerParam;
                    if (tpam.StartsWith("javascript:", StringComparison.CurrentCultureIgnoreCase))
                        tpam = tpam.Substring("javascript:".Length);
                    else
                        tpam = string.Format("\"{0}\"", tpam);

					IAction firstAction = actions[0];
                    if(TriggerParam == null)
						ClientClick = string.Format(@"{3}{0}BizProc.triggerEvent(""{1}"",""{4}"");{2}", firstAction.ParentProcess.Id, WidgetId, after, m_clientScript, firstAction.Id);
                    else
						ClientClick = string.Format(@"{3}{0}BizProc.triggerEvent(""{1}"",""{4}"", {5});{2}", firstAction.ParentProcess.Id, WidgetId, after, m_clientScript, firstAction.Id, tpam);

					Page.ClientScript.RegisterStartupScript(typeof(ActionButton), "ActionGlobal", s_globalScript, true);
				}
			}
			base.OnPreRender(e);

			//Because the base button will use the Visible property based on the Action states, we
			//need to ensure that it is always visible when ajax is being used so that the button DHTML 
			//is always present for the script.  the script will hide/show the button as needed.
			if (setupScript)
			{
				Page.ClientScript.RegisterStartupScript(typeof(ActionButton), WidgetId,
					string.Format(s_setupScript, actions[0].ParentProcess.Id, WidgetId,
					!InnerVisible ? "c.dhtmlObj.style.display = 'none';" : ""), true);
				InnerVisible = true;
			}
		}

		public void setState(XmlElement clientState)
		{
		}

		public void getState(XmlElement clientState, string pageHtml)
		{
			if (m_canceledTrigger)
				return;

			IAction action = getActionForAvailability();
			if (action != null)
			{
				clientState.SetAttribute("enabled", action.Enabled.ToString());
				clientState.SetAttribute("visible", (!(action.Availability == ActionAvailability.none)).ToString());
			}
			else
			{
				clientState.SetAttribute("action", "");
				clientState.SetAttribute("enabled", false.ToString());
			}
			if (Text != null && Text != "")
				clientState.SetAttribute("label", Text);
		}

		public void processAjaxEvent(XmlElement eventInfo)
		{
			if (eventInfo.GetAttribute("event").CompareTo("bizObjSelected") == 0)
			{
				string bizObjId = eventInfo.GetAttribute("value");
				ActiveBizProc bizproc = BPC.getActiveBizProc(State.ParentBizProcIds[0]);
				bizproc.BizProc.selectBizObj(bizObjId, this);
			}
			else
			{
				string oldTrigParam = null;
				string xml = eventInfo.GetAttribute("value");
				if (!Swaf.Cmn.IsEmpty(xml))
				{
					oldTrigParam = TriggerParam;
					TriggerParam = xml;
				}
				OnClick();
				if (oldTrigParam != null)
					TriggerParam = oldTrigParam;
			}
		}

		public bool NeedToGenerateHtmlWithServerControls
		{
			get { return false; }
		}
		public bool CreateOnLoad { set{m_createActiveOnLoad = true; } }
	}
}
